'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-08-02 22:48:24
@LastEditTime: 2020-03-10 19:55:18
@LastEditors: Please set LastEditors
'''
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import find_data, get_info, get_current_user_id
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, DataProcess, get_cur_time
from ...service.common import get_area_id, get_current_organization_id, date_str_to_date, get_string_time, get_str_to_age
from ...service.buss_pub.personnel_organizational import UserCategory, UserType
from ...pao_python.pao.remote import JsonRpc2Error
from ...service.buss_mis.financial_account import FinancialAccountObject
from ...service.constant import AccountType, PayType, PayStatue, AccountStatus, plat_id
from ...models.financial_manage import FinancialAccount
from ...service.buss_pub.message_manage import MessageManageService

'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-08-02 22:48:24
@LastEditTime: 2019-08-02 22:48:24
@LastEditors: your name
'''
# -*- coding: utf-8 -*-

'''
预约登记函数
'''


class ReservationRegistration:
    ''' 预约记录对象类 '''

    def create_reservation_registration(self, reservation_registration):
        ''' 预约记录 '''
        # 状态
        self.state = reservation_registration['state']
        # 备注
        self.remarks = reservation_registration['remarks']
        # 是否黑名单
        self.is_blacklist = reservation_registration['is_blacklist']
        # 接待员
        self.receptionist = reservation_registration['receptionist']
        # 预约时间
        self.reservation_date = reservation_registration['reservation_date']

    def get_reservation_registration(self, reservation_registration):
        ''' 获取人员 '''
        self.create_reservation_registration(reservation_registration)
        self.reservation_registration_info = {**reservation_registration}
        return self.__dict__


class ReservationRegistrationService(MongoService):
    ''' 预约登记 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.MessageManageService = MessageManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_reservation_registration_list(self, org_list, condition, page, count):
        '''获取预约登记列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'state', 'start_date', 'end_date',
                'elder_name', 'receptionist']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id']) & (C('state') == values['state']) & (C('bill_status') == 'valid') & (C('organization_id').inner(org_list)))\
            .lookup_bill('PT_User', 'receptionist_id', 'id', 'receptionist')\
            .inner_join_bill('PT_User', 'elder_id', 'id', 'basic_information')\
            .inner_join_bill('PT_User', 'organization_id', 'id', 'organization_info')\
            .lookup_bill('PT_Behavioral_Competence_Assessment_Record', 'assessment_id', 'id', 'preliminary_assessment')\
            .lookup_bill('PT_Requirement_Record', 'requirement_id', 'id', 'residence_demand')\
            .add_fields({
                'receptionist': '$receptionist.name',
                'name': '$basic_information.name',
                'age': '$basic_information.personnel_info.age',
                'sex': '$basic_information.personnel_info.sex',
                'telephone': '$basic_information.personnel_info.telephone',
                'family_name': '$basic_information.personnel_info.family_name',
                'score': '$preliminary_assessment.total_score',
                'id_card': '$basic_information.id_card',
                'organization_address': '$organization_info.address',
                'organization_name': '$organization_info.name',
            })\
            .match_bill((C('name').like(values['elder_name']))
                        & (C('reservation_date') > as_date(values['start_date']))
                        & (C('reservation_date') < as_date(values['end_date']))
                        & (C('receptionist').like(values['receptionist'])))\
            .sort({'modify_date': -1})\
            .project({'_id': 0, 'basic_information._id': 0, 'receptionist._id': 0, 'preliminary_assessment._id': 0, 'residence_demand._id': 0, 'organization_info._id': 0})
        res = self.page_query(
            _filter, 'PT_Reservation_Registration', page, count)
        print(res)
        for i, x in enumerate(res['result']):
            if 'basic_information' in res['result'][i] and 'personnel_info' in res['result'][i]['basic_information']:
                data = res['result'][i]['basic_information']['personnel_info']
                date_res = get_string_time(data['date_birth'], '%Y-%m-%d')
                res['result'][i]['date_birth'] = date_res
                res['result'][i]['age'] = get_str_to_age(date_res)
        return res

    def update_reservation_registration(self, reservation_registration):
        '''# 新增/修改预约登记'''
        res = 'Fail'
        basic_information = {}
        preliminary_assessment = {}
        residence_demand = {}
        if 'date_birth' in reservation_registration['basic_information']['personnel_info'].keys():
            date = reservation_registration['basic_information']['personnel_info']
            date['date_birth'] = date_str_to_date(date['date_birth'])

        def process_func(db):
            nonlocal res, basic_information, preliminary_assessment, residence_demand
            if 'id' in reservation_registration.keys():
                # 预约数据
                reservation_registrations = reservation_registration['reservation_registration']
                # 基本资料数据拼接
                basic_information = reservation_registration['basic_information']
                # 初步评估数据拼接
                preliminary_assessment = reservation_registration['preliminary_assessment']
                # 入住需求数据拼接
                residence_demand = reservation_registration['residence_demand']
                _filter = MongoBillFilter()
                _filter.match_bill((C('id') == reservation_registration['id']))\
                    .project({'_id': 0})
                res = self.page_query(
                    _filter, 'PT_Reservation_Registration', None, None)
                if len(res['result']):
                    basic_information['id'] = res['result'][0]['elder_id']
                    preliminary_assessment['id'] = res['result'][0]['assessment_id']
                    residence_demand['id'] = res['result'][0]['requirement_id']
                    # 统一调用add_bill做插入
                    bill_res = self.bill_manage_service.add_bill(OperationType.update.value,
                                                                 TypeId.reservationRegistration.value, [reservation_registrations, basic_information, preliminary_assessment, residence_demand], ['PT_Reservation_Registration', 'PT_User', 'PT_Behavioral_Competence_Assessment_Record', 'PT_Requirement_Record'])
                # bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                #                                             TypeId.reservationRegistration.value, reservation_registration, 'PT_Reservation_Registration')
                # user_bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                #                                                  TypeId.reservationRegistration.value, basic_information, 'PT_User')
                # behavioral_competence_assessment_record_bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                #                                                                                     TypeId.reservationRegistration.value, preliminary_assessment, 'PT_Behavioral_Competence_Assessment_Record')
                # requirement_record_bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                #                                                                TypeId.reservationRegistration.value, residence_demand, 'PT_Requirement_Record')
                if bill_res:
                    res = 'Success'
            else:
                # id = get_info({})
                # 长者基本资料数据拼接
                _filter = MongoBillFilter()
                # reservation_registration['basic_information']['personnel_info']['personnel_category'] = UserCategory.Elder
                reservation_registration['basic_information']['admin_area_id'] = get_area_id(
                    self, _filter)  # 添加行政区域id
                # reservation_registration['basic_information']['id_card_type'] = '身份证'
                basic_information = reservation_registration['basic_information']
                # basic_information = {
                #     'personnel_info': reservation_registration['basic_information']['personnel_info'],
                #     'personnel_type': reservation_registration['basic_information']['personnel_type'],
                #     'name': reservation_registration['basic_information']['name'],
                #     'telephone': reservation_registration['basic_information']['telephone'],
                # }

                # if 'remarks' in reservation_registration['basic_information'].keys():
                #     basic_information['remarks'] = reservation_registration['basic_information']['remarks']
                _filter_user = MongoBillFilter()
                _filter_user.match_bill((C('personnel_info.personnel_category') == UserCategory.Elder) & (C('personnel_info.id_card') == basic_information['id_card']))\
                    .project({'_id': 0})
                res = self.page_query(
                    _filter_user, 'PT_User', None, None)
                print('是否存在长者', res, _filter_user.filter_objects)
                # 判断是否已存在该长者
                if len(res['result']):
                    basic_information['id'] = res['result'][0]['id']
                    _filter_reservation = MongoBillFilter()
                    _filter.match_bill(
                        C('elder_id') == basic_information['id'])
                    res_reservation = self.query(
                        _filter_reservation, 'PT_Reservation_Registration')
                    print('<<<<<<<<<<<', res_reservation)
                    if len(res_reservation):
                        raise JsonRpc2Error(-36101, '该长者已经预约过，不能重复预约')
                    user_bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                                     TypeId.reservationRegistration.value, basic_information, 'PT_User')
                else:
                    basic_information = get_info(
                        basic_information, self.session)
                    user_bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                                     TypeId.reservationRegistration.value, basic_information, 'PT_User')

                # 初步评估数据拼接
                preliminary_assessment = {
                    'elder': basic_information['id'],
                    'template': reservation_registration['preliminary_assessment']['template'],
                    'project_list': reservation_registration['preliminary_assessment']['project_list'],
                    'total_score': reservation_registration['preliminary_assessment']['total_score'],
                    'assessment_opinions': reservation_registration['preliminary_assessment']['assessment_opinions'],
                    'create_date': get_cur_time()
                }
                preliminary_assessment = get_info(
                    preliminary_assessment, self.session)
                # 入住需求数据拼接(等需求的结构改好再做绑定)
                # residence_demand = get_info(
                #     **reservation_registration['residence_demand'])
                # residence_demand['elder'] = basic_information['id']
                # 预约数据拼接
                reservation_registrations = {
                    'remarks': reservation_registration['reservation_registration']['remarks'],
                    'state': reservation_registration['reservation_registration']['state'],
                    'reservation_date': get_cur_time(),
                    'is_blacklist': '否',
                    'elder_id': basic_information['id'],
                    'receptionist_id': get_current_user_id(self.session),
                    'assessment_id': preliminary_assessment['id'],
                    'requirement_id': 'cx',
                }
                reservation_registrations = get_info(
                    reservation_registrations, self.session)
                # 新增账户信息（1个机构储蓄、1个app储蓄、1个真实账户）
                # 机构储蓄对象
                org_id = get_current_organization_id(self.session)
                org_account_data = FinancialAccountObject(
                    AccountType.account_recharg_wel, basic_information['id'], org_id, AccountStatus.normal, 1, AccountType.account_recharg_wel, {}, 0)
                org_account = get_info(
                    org_account_data.to_dict(), self.session)
                # app储蓄对象
                app_account_data = FinancialAccountObject(
                    AccountType.account_recharg_app, basic_information['id'], plat_id, AccountStatus.normal, 2, AccountType.account_recharg_app, {}, 0)
                app_account = get_info(
                    app_account_data.to_dict(), self.session)
                # 真实账户对象
                real_account_data = FinancialAccountObject(
                    AccountType.account_real, basic_information['id'], None, AccountStatus.normal, 3, AccountType.account_real, {}, 0)
                real_account = get_info(
                    real_account_data.to_dict(), self.session)
                # 补贴账户对象
                subsidy_account_data = FinancialAccountObject(
                    AccountType.account_subsidy, basic_information['id'], None, AccountStatus.normal, 4, AccountType.account_subsidy, {}, 0)
                subsidy_account = get_info(
                    subsidy_account_data.to_dict(), self.session)
                # 统一调用add_bill做插入
                bill_res = self.bill_manage_service.add_bill(OperationType.add.value,
                                                             TypeId.reservationRegistration.value, [[reservation_registrations], [preliminary_assessment], [residence_demand], [org_account, app_account, real_account, subsidy_account]], ['PT_Reservation_Registration', 'PT_Behavioral_Competence_Assessment_Record', 'PT_Requirement_Record', FinancialAccount().name])
                if bill_res and user_bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def app_update_reservation_registration(self, reservation_registration):
        '''# app新增/修改预约登记'''
        res = 'Fail'
        record_id = ''
        state = ''
        user = reservation_registration
        if 'id_card' in reservation_registration.keys():
            # 获取选择机构所属的行政区划id
            _filter = MongoBillFilter()
            _filter.match_bill((C('id') == reservation_registration['organization_id']))\
                .project({'_id': 0})
            res_org = self.query(_filter, 'PT_User')
            if len(res_org) > 0:
                reservation_registration['admin_id'] = res_org[0]['admin_area_id']
            _filter = MongoBillFilter()
            _filter.match_bill((C('id_card') == reservation_registration['personnel_info']['id_card']))\
                .project({'_id': 0})
            res = self.page_query(
                _filter, 'PT_User', None, None)
            print("查询结果>>>>>>>>", res)
            # 判断是否已存在该长者
            if len(res['result']) > 0:
                user['id'] = res['result'][0]['id']
                # 存在
                print(reservation_registration['organization_id'])
                print(res['result'][0]['id'])
                _filter = MongoBillFilter()
                _filter.match_bill((C('elder_id') == res['result'][0]['id']) & (C('organization_id') == reservation_registration['organization_id']))\
                    .project({'_id': 0})
                res_record = self.page_query(
                    _filter, 'PT_Reservation_Registration', None, None)
                print("查询结果2>>>>>>>>", res_record)
                if len(res_record['result']) > 0:
                    # 存在预约信息
                    record_id = res_record['result'][0]['id']
                    state = res_record['result'][0]['state']
                    print("预约记录状态", state)
                # reservation_registration['id'] = res['result'][0]['id']
                # user_bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                #                                                  TypeId.reservationRegistration.value, reservation_registration, 'PT_User')
            else:
                return '预约长者不存在，请核实！'
                # user = get_info(
                #     reservation_registration, self.session)
                # # 新增账户信息（1个机构储蓄、1个app储蓄、1个真实账户、1个补贴账户）
                # # 机构储蓄对象
                # org_account_data = FinancialAccountObject(
                #     AccountType.account_recharg_wel, user['id'], user['organization_id'], AccountStatus.normal, 1, AccountType.account_recharg_wel, {}, 0)
                # org_account = get_info(
                #     org_account_data.to_dict(), self.session)
                # # app储蓄对象
                # app_account_data = FinancialAccountObject(
                #     AccountType.account_recharg_app, user['id'], plat_id, AccountStatus.normal, 2, AccountType.account_recharg_app, {}, 0)
                # app_account = get_info(
                #     app_account_data.to_dict(), self.session)
                # # 真实账户对象
                # real_account_data = FinancialAccountObject(
                #     AccountType.account_real, user['id'], None, AccountStatus.normal, 3, AccountType.account_real, {}, 0)
                # real_account = get_info(
                #     real_account_data.to_dict(), self.session)
                # # 补贴账户对象
                # subsidy_account_data = FinancialAccountObject(
                #     AccountType.account_subsidy, user['id'], None, AccountStatus.normal, 4, AccountType.account_subsidy, {}, 0)
                # subsidy_account = get_info(
                #     subsidy_account_data.to_dict(), self.session)

                # user_bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                #                                                  TypeId.reservationRegistration.value, [[user], [org_account, app_account, real_account, subsidy_account]], ['PT_User', FinancialAccount().name])
            # 预约数据拼接
            reservation_registrations = {
                'remarks': user['remarks'],
                'state': '网上预约',
                'reservation_date': get_cur_time(),
                'is_blacklist': '否',
                'elder_id': user['id'],
                'receptionist_id': get_current_user_id(self.session),
                'requirement_id': 'cx',
                'organization_id': reservation_registration['organization_id']
            }
            if (record_id != '' and record_id != None):
                if (state == "现场预约"):
                    res = '已经现场预约过了'
                    return res
                else:
                    reservation_registrations['id'] = record_id
                    bill_res = self.bill_manage_service.add_bill(OperationType.update.value,
                                                                 TypeId.reservationRegistration.value, reservation_registrations, 'PT_Reservation_Registration')
            else:
                reservation_registrations = get_info(
                    reservation_registrations, self.session)
                reservation_registrations['organization_id'] = reservation_registration['organization_id']
                # 统一调用add_bill做插入
                bill_res = self.bill_manage_service.add_bill(OperationType.add.value,
                                                             TypeId.reservationRegistration.value, reservation_registrations, 'PT_Reservation_Registration')
            if bill_res:
                # 插入一个消息提醒
                self.MessageManageService.add_new_message({
                    # 床位管理标识
                    "business_type": 'rservation_registration',
                    # 业务ID
                    "business_id": reservation_registrations['id'],
                    "organization_id": reservation_registration['organization_id']
                })
                res = 'Success'
        return res

    def delete_reservation_registration(self, reservation_registration_ids):
        '''删除预约登记接口

        Arguments:
            reservation_registration_ids   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(reservation_registration_ids, str):
                ids.append(reservation_registration_ids)
            else:
                ids = reservation_registration_ids
            for reservation_registration_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Reservation_Registration', {
                    'id': reservation_registration_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.reservationRegistration.value, data[0], 'PT_Reservation_Registration')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
